#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>


struct ListNode {
    int val;
   struct ListNode *next;
};


struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {

    struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* cur = node;
    while (list1 && list2) {
        if (list1->val < list2->val) {
            cur->next = list1;
            cur = cur->next;
            list1 = list1->next;
        }
        else {
            cur->next = list2;
            cur = cur->next;
            list2 = list2->next;
        }
    }
    if (list1) {
        cur->next = list1;
    }
    else if (list2) {
        cur->next = list2;
    }
    else {
        free(node);
        return NULL;
    }
    struct ListNode* head = node->next;
    free(node);
    return head;
}